package cz.techi;

import java.net.URL;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import android.util.Log;
import java.util.ArrayList;

public class ScheduleLoader {

	private String xname;

	private String errorMessage;

	public ScheduleLoader(String xname) {
		this.xname = xname;
	}

	public String getErrorMessage() {
		return errorMessage;
	}

	public Subject[] getSubjects() {
		ArrayList<Subject> subjects = new ArrayList<Subject>();

		try {

			URL url = new URL("http://www.techi.cz/rozvrh.php?xname=" + xname
					+ "&lang=cz");
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document doc = db.parse(new InputSource(url.openStream()));
			doc.getDocumentElement().normalize();

			NodeList nodeList = doc.getElementsByTagName("subject");

			for (int i = 0; i < nodeList.getLength(); i++) {

				Node node = nodeList.item(i);

				Subject subject = new Subject();
				subject.ident = ((Element) node).getElementsByTagName("ident")
						.item(0).getTextContent();
				subject.name = ((Element) node).getElementsByTagName("name")
						.item(0).getTextContent();
				subject.teacher = ((Element) node)
						.getElementsByTagName("teacher").item(0)
						.getTextContent();
				subject.room = ((Element) node).getElementsByTagName("room")
						.item(0).getTextContent();
				subject.type = ((Element) node).getElementsByTagName("class")
						.item(0).getTextContent();
				subject.from = ((Element) node).getElementsByTagName("from")
						.item(0).getTextContent();
				subject.to = ((Element) node).getElementsByTagName("to")
						.item(0).getTextContent();
				subject.day = ((Element) node).getElementsByTagName("day")
						.item(0).getTextContent();
				subject.hour = Integer.parseInt(((Element) node)
						.getElementsByTagName("hour").item(0).getTextContent());

				subjects.add(subject);
			}

			if (nodeList.getLength() == 0) {
				errorMessage = doc.getElementsByTagName("error").item(0)
						.getTextContent();
				Log.v("myShit", errorMessage);
			}

		}

		catch (Exception e) {
			this.errorMessage = e.getMessage();
			e.printStackTrace();
			Log.v("myShit", "exception" + e.getMessage());
		}

		return subjects.toArray(new Subject[subjects.size()]);
	}
}
